/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.boxin.ims.modules.wechat.service;

import java.util.List;

import org.apache.commons.lang3.StringEscapeUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boxin.framework.base.dao.DaoHelper;
import com.boxin.ims.modules.wechat.dao.QuestionDao;
import com.boxin.ims.modules.wechat.entity.Question;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.service.BaseService;

/**
 * 调查问卷问题Service
 * @author XiaoQian
 * @version 2014-05-09
 */
@Component
@Transactional(readOnly = true)
public class QuestionService extends BaseService {

	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(QuestionService.class);
	
	@Autowired
	private QuestionDao questionDao;
	
	@Autowired
	DaoHelper daoHelper;
	
	public Question get(Long id) {
		return questionDao.findOne(id);
	}
	
	public Page<Question> find(Page<Question> page, Question question) {
		DetachedCriteria dc = questionDao.createDetachedCriteria();
		dc.createAlias("questionnaire", "questionnaire");
		if (question.getUser()!=null && question.getUser().getId()>0){
			dc.add(Restrictions.eq("user.id", question.getUser().getId()));
		}
		if (question.getQuestionnaire()!=null && question.getQuestionnaire().getId()>0){
			dc.add(Restrictions.eq("questionnaire.id", question.getQuestionnaire().getId()));
		}
		dc.addOrder(Order.desc("id"));
		return questionDao.find(page, dc);
	}
	
	public List<Question> findByQuestionnaireId(Long questionnaireId){
		DetachedCriteria dc = questionDao.createDetachedCriteria();
		dc.createAlias("questionnaire", "questionnaire");
		dc.add(Restrictions.eq("questionnaire.id", questionnaireId));
		dc.addOrder(Order.desc("sort"));
		return questionDao.find(dc);
	}
	
	public List<Question> findVoterByQuestionnaireId(Long questionnaireId){
		DetachedCriteria dc = questionDao.createDetachedCriteria();
		dc.createAlias("questionnaire", "questionnaire");
		dc.add(Restrictions.eq("questionnaire.id", questionnaireId));
		dc.addOrder(Order.desc("number"));
		return questionDao.find(dc);
	}
	
	@Transactional(readOnly = false)
	public void save(Question question) {
		question.setQuestion(StringEscapeUtils.unescapeHtml4(question.getQuestion()) );
		questionDao.save(question);
	}
	
	
	@Transactional(readOnly = false)
	public void delete(Long id) {
		questionDao.deleteById(id);
	}
	
}
